#include "json.h"
#include <rtthread.h>

extern int cm_switch;
static char *lat_point;                 //经纬度内存指针
static char *lon_point;

void Json_Add(char list[],char name[],void *data){
	char buf[200] = "";
	int i,n,sym;
	
	sym=-1;
	n = rt_strlen(list);
	if(n == 0){
	    /* id*/
        rt_sprintf(buf,"{\\\"%s\\\":%d}",name,1);
        strcpy(list,buf);
	}
	else{
		for(i=n-1;i>=0;i--){
			if(list[i] == '}'){
				sym = i;
			}
		}

		list[sym] = '\0';
		if(rt_strcmp(name,"lat") == 0){
		    rt_sprintf(buf,"%s\\,\\\"%s\\\":%s}",list,name,(char*)data);
			strcpy(list,buf);
			lat_point = data;                   //记录纬度内存地址
		}
		else if(rt_strcmp(name,"lon") == 0){
		    rt_sprintf(buf,"%s\\,\\\"%s\\\":%s}",list,name,(char*)data);
		    strcpy(list,buf);
		    lon_point = data;                   //记录经度内存地址
		}
		else if(rt_strcmp(name,"plat") == 0 || rt_strcmp(name,"plon") == 0){
		    rt_sprintf(buf,"%s\\,\\\"%s\\\":%s}",list,name,(char*)data);
            strcpy(list,buf);
		}
		else if(rt_strcmp(name, "voice") == 0 || rt_strcmp(name, "log") == 0){
		    rt_sprintf(buf,"%s\\,\\\"%s\\\":\\\"%s\\\"}",list,name,(char*)data);
            strcpy(list,buf);
		}
		else if(rt_strcmp(name,"grp") == 0 || rt_strcmp(name, "way") == 0){
		    rt_sprintf(buf, "%s\\,\\\"%s\\\":%d",list,name,(short*)data);
		    strcpy(list,buf);
		}
		else if(rt_strcmp(name, "warn") == 0){
		    rt_sprintf(buf, "%s\\,\\\"%s\\\":\\\"%s\\\"}",list,name,(char*)data);
            strcpy(list,buf);
		}
		else{
		    rt_kprintf("json null!!\n");
		}

		memset(list,'\0',sizeof(char)*n);
		strcpy(list,buf);
	}
}

void Json_Sent(char *topic,char list[]){
    /* WIFI发送*/
    if(cm_switch == 0){
        char buf[200] = "";

        rt_sprintf(buf,"AT+MQTTPUB=0,\"%s\",\"%s\",0,0",topic,list);

        WIFI_ATCMD(buf);
    }/* 4G发送*/
    else{
        char buf[200] = "";
        short count = 0;
        short length = strlen(list);
        for(int i=0;i<length;i++){
            if(list[i] != '\\'){
                buf[count++] = list[i];
            }
        }

        M100P_Sent(buf);
    }
}

